<template>
  <div class="short-video-management">
    <div class="header">
      <h2>短视频管理</h2>
      <div class="header-actions">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索视频标题或描述"
          style="width: 200px; margin-right: 10px;"
          clearable
          @clear="fetchShortVideoList"
          @keydown.enter="fetchShortVideoList"
        >
          <template #append>
            <el-button :icon="Search" @click="fetchShortVideoList" />
          </template>
        </el-input>
        <el-button type="primary" @click="handleAddVideo">新增视频</el-button>
        <el-button type="success" @click="fetchShortVideoList" :loading="loading">刷新</el-button>
        <el-button
            type="danger"
            @click="handleBatchDelete"
            :disabled="selectedVideos.length === 0"
        >
          批量删除({{ selectedVideos.length }})
        </el-button>
      </div>
    </div>
    
    <div class="table-container">
      <el-table
        :data="videoList"
        style="width: 100%"
        v-loading="loading"
        element-loading-text="加载中..."
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="video_id" label="视频ID" width="100" sortable />
        <el-table-column label="封面" width="100">
          <template #default="scope">
            <div class="cover-container" @click="handlePlayVideo(scope.row)">
              <el-image 
                :src="getCoverImageUrl(scope.row)" 
                fit="cover"
                :preview-src-list="[getCoverImageUrl(scope.row)]"
                preview-teleported
                style="width: 60px; height: 60px; border-radius: 4px;"
              />
              <div class="play-overlay">
                <el-icon class="play-icon" :size="14"><VideoPlay /></el-icon>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" min-width="150" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.title || '无标题' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.description || '无描述' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="author" label="作者" width="120">
          <template #default="scope">
            <div class="author-info">
              <el-avatar 
                :size="30" 
                :src="scope.row.author?.avatar"
              >
                {{ scope.row.author?.name?.charAt(0) }}
              </el-avatar>
              <span class="author-name">{{ scope.row.author?.name || '未知' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="统计数据" width="110">
          <template #default="scope">
            <div class="stats">
              <div class="stat-item">
                <el-icon :size="14"><VideoPlay /></el-icon>
                <span>{{ scope.row.play_count || 0 }}</span>
              </div>
              <div class="stat-item">
                <el-icon :size="14"><Star /></el-icon>
                <span>{{ scope.row.like_count || 0 }}</span>
              </div>
              <div class="stat-item">
                <el-icon :size="14"><ChatLineSquare /></el-icon>
                <span>{{ scope.row.comment_count || 0 }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="150" sortable>
          <template #default="scope">
            {{ formatDate(scope.row.created_at || scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="360" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleManageComments(scope.row)">评论管理</el-button>
            <el-button size="small" @click="handleManageLikes(scope.row)">点赞管理</el-button>
            <el-button size="small" @click="handleViewDetails(scope.row)">详情</el-button>
            <el-button size="small" @click="handleEditVideo(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDeleteVideo(scope.row)"
              :loading="deletingVideoId === scope.row.video_id"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.limit"
        :page-sizes="[50, 500, 1000]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    

    
    <!-- 视频编辑/新增弹窗 -->
    <ShortVideoDialog
      v-model="videoDialogVisible"
      :video-data="editingVideo"
      :is-edit-mode="isEditMode"
      @success="handleVideoSuccess"
    />
    
    <!-- 评论管理弹窗 -->
    <CommentManagementDialog
      v-model="commentManagementVisible"
      :video-data="currentVideo"
    />
    
    <!-- 点赞管理弹窗 -->
    <LikeManagementDialog
      v-model="likeManagementVisible"
      :video-data="currentVideo"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Star, ChatLineSquare, VideoPlay } from '@element-plus/icons-vue'
import ShortVideoDialog from '@/views/Console/ShortVideoManagement/ShortVideoDialog.vue'
import CommentManagementDialog from '@/views/Console/ShortVideoManagement/CommentManagementDialog.vue'
import LikeManagementDialog from '@/views/Console/ShortVideoManagement/LikeManagementDialog.vue'
import type { ShortVideo, ShortVideoComment } from '@/api/modules/shortVideo'
import defaultCoverImage from '@/assets/imgs/video.png'
import { 
  getShortVideoList, 
  deleteShortVideo, 
  getShortVideoById,
  batchDeleteShortVideo
} from '@/api/modules/shortVideo'

const router = useRouter()

// 视频列表
const videoList = ref<ShortVideo[]>([])

// 加载状态
const loading = ref(false)

// 删除视频时的加载状态
const deletingVideoId = ref<number | null>(null)

// 选中的视频
const selectedVideos = ref<ShortVideo[]>([])

// 搜索关键词
const searchKeyword = ref('')

// 排序字段
const sortField = ref('createdAt')

// 排序方式
const sortOrder = ref('DESC')

// 弹窗相关
const videoDialogVisible = ref(false)
const isEditMode = ref(false)
const editingVideo = ref<ShortVideo | null>(null)

// 管理弹窗相关
const commentManagementVisible = ref(false)
const likeManagementVisible = ref(false)
const currentVideo = ref<ShortVideo | null>(null)

// 分页信息
const pagination = ref({
  page: 1,
  limit: 50,
  total: 0
})

// 格式化日期
const formatDate = (dateString: string | undefined) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN');
};

// 处理排序变化
const handleSortChange = (sort: { column: any; prop: string; order: string }) => {
  if (sort.prop) {
    sortField.value = sort.prop;
    sortOrder.value = sort.order === 'ascending' ? 'ASC' : 'DESC';
  } else {
    sortField.value = 'createdAt';
    sortOrder.value = 'DESC';
  }
  fetchShortVideoList();
};

// 获取视频列表
const fetchShortVideoList = async () => {
  loading.value = true
  try {
    const response = await getShortVideoList({
      page: pagination.value.page,
      limit: pagination.value.limit,
      keyword: searchKeyword.value || undefined,
      sort_field: sortField.value,
      sort_order: sortOrder.value
    })
    
    videoList.value = response.data?.list || []
    if (response.data?.pagination) {
      pagination.value.total = response.data.pagination.total || 0
    }
  } catch (error) {
    console.error('获取短视频列表失败:', error)
    // 错误信息已经在request.ts的响应拦截器中处理过了，这里不需要再显示
  } finally {
    loading.value = false
  }
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pagination.value.limit = val
  pagination.value.page = 1 // 重置到第一页
  fetchShortVideoList()
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  pagination.value.page = val
  fetchShortVideoList()
}

// 处理选择变化
const handleSelectionChange = (val: ShortVideo[]) => {
  selectedVideos.value = val
}

// 处理查看详情
const handleViewDetails = (video: ShortVideo) => {
  router.push(`/short-video-management/detail/${video.video_id}`)
}

// 处理编辑视频
const handleEditVideo = (video: ShortVideo) => {
  editingVideo.value = video
  isEditMode.value = true
  videoDialogVisible.value = true
}

// 处理新增视频
const handleAddVideo = () => {
  editingVideo.value = null
  isEditMode.value = false
  videoDialogVisible.value = true
}

// 处理视频操作成功（新增或编辑）
const handleVideoSuccess = () => {
  videoDialogVisible.value = false
  // 重新获取视频列表
  fetchShortVideoList()
  
  // 如果当前正在查看详情，也需要更新详情
  if (currentVideo.value && editingVideo.value && currentVideo.value.video_id === editingVideo.value.video_id) {
    getShortVideoById({ video_id: editingVideo.value.video_id }).then(response => {
      currentVideo.value = response.data || null
    }).catch(error => {
      console.error('获取视频详情失败:', error)
    })
  }
}

// 处理播放视频
const handlePlayVideo = (video: ShortVideo) => {
  router.push(`/short-video-management/detail/${video.video_id}`)
}

// 处理管理评论
const handleManageComments = (video: ShortVideo) => {
  currentVideo.value = video
  commentManagementVisible.value = true
}

// 处理管理点赞
const handleManageLikes = (video: ShortVideo) => {
  currentVideo.value = video
  likeManagementVisible.value = true
}

// 处理删除视频
const handleDeleteVideo = async (video: ShortVideo) => {
  ElMessageBox.confirm(
    `确定要删除视频"${video.title || '无标题'}"吗？此操作不可恢复！`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    } as any
  )
  .then(async () => {
    if (!video.video_id) return
    
    deletingVideoId.value = video.video_id
    try {
      await deleteShortVideo({ video_id: video.video_id })
      ElMessage.success('删除成功')
      // 重新获取视频列表
      fetchShortVideoList()
    } catch (error) {
      console.error('删除视频失败:', error)
      // 错误信息已经在request.ts的响应拦截器中处理过了，这里不需要再显示
    } finally {
      deletingVideoId.value = null
    }
  })
  .catch(() => {
    // 用户取消删除
  })
}

// 处理批量删除视频
const handleBatchDelete = async () => {
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedVideos.value.length} 个视频吗？此操作不可恢复！`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    } as any
  )
  .then(async () => {
    try {
      const videoIds = selectedVideos.value.map(video => video.video_id!).filter(id => id !== undefined);
      if (videoIds.length === 0) {
        ElMessage.warning('请选择有效的视频进行删除');
        return;
      }
      
      // 使用批量删除接口
      await batchDeleteShortVideo({ video_ids: videoIds });
      
      ElMessage.success(`成功删除${videoIds.length}个视频`);
      // 清空选中项
      selectedVideos.value = [];
      // 重新获取视频列表
      await fetchShortVideoList();
    } catch (error) {
      console.error('批量删除视频失败:', error);
      // 错误信息已经在request.ts的响应拦截器中处理过了，这里不需要再显示
    }
  })
  .catch(() => {
    // 用户取消删除
  })
}

// 获取封面图片URL
const getCoverImageUrl = (video: ShortVideo) => {
  if (video.cover_image?.fileurl) {
    return video.cover_image.fileurl;
  }
  return defaultCoverImage;
};

// 组件挂载时获取视频列表
onMounted(() => {
  fetchShortVideoList()
})
</script>

<style scoped>
.short-video-management {
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  height: 100%;
  overflow: auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
}

.table-container {
  height: calc(100% - 150px);
  overflow: auto;
}

.cover-container {
  position: relative;
  width: 60px;
  height: 60px;
  cursor: pointer;
}

.play-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.cover-container:hover .play-overlay {
  opacity: 1;
}

.play-icon {
  font-size: 20px;
  color: white;
}

.author-info {
  display: flex;
  align-items: center;
}

.author-name {
  margin-left: 5px;
  font-size: 12px;
}

.stats {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.stat-item {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.stat-item .el-icon {
  margin-right: 5px;
  font-size: 14px;
}
.pagination-container {
  background-color: white;
  display: flex;
  justify-content: flex-end;
}
</style>